/*
 * @Description: 文件合并弹窗
 * @Author: Zzt
 * @Date: 2022-10-29 11:43:18
 * @LastEditTime: 2022-11-02 19:22:59
 */

import { useEffect, useState } from 'react';
import { Button, Divider, InputNumber, message, Modal, Select, Space } from 'antd';
import { v4 as uuidv4 } from 'uuid';
import { useLevelTableContext } from '../../contexts/LevelTableContext';
import { fetchBoxSpecList } from '@/api/box/specifications';
import { IArchiveBox, IBoxSpec } from '@/interfaces/box';
import { editItemById, selectItemByKey } from '@/utils/list';
import { IPackBoxParams, packBoxMethod } from '@/api/box/boxMgt';

class BoxInfo {
  id: string;
  // 盒内文件数
  fileNum: number;
  // 盒内文件页数
  pageNum: number;
  // 盒规格ID
  specId: number;
  // 条目id集合
  entryIdList: number[];

  constructor() {
    this.id = uuidv4();
    this.entryIdList = [];
  }

  setFileNum(fileNum: number, pageNum: number, idList: number[]): void {
    this.fileNum = fileNum;
    this.pageNum = pageNum;
    this.entryIdList = idList;
  }

  setSpecId(specId: number): void {
    this.specId = specId;
  }
}

interface IPackBoxDialogProps {
  visible: boolean;
  onClose: any;
  selectObjs: any[];
}

const PackBoxDialog = (props: IPackBoxDialogProps) => {
  const { visible, onClose, selectObjs } = props;
  const { baseInfo } = useLevelTableContext();

  // 共分X盒
  const [boxNum, setBoxNum] = useState(1);
  // 盒规格列表
  const [boxSpecList, setBoxSpecList] = useState<IBoxSpec[]>([]);
  // 盒列表
  const [boxList, setBoxList] = useState<BoxInfo[]>([]);

  useEffect(() => {
    if (visible) {
      setBoxNum(1);
      setBoxList([new BoxInfo()]);
      getBoxSpec();
    }
  }, [visible]);

  useEffect(() => {
    const list = Array(boxNum)
      .fill(1)
      .map(() => new BoxInfo());
    setBoxList(list);
  }, [boxNum]);

  // 获取盒规格列表
  const getBoxSpec = () => {
    fetchBoxSpecList({}).then((res) => {
      setBoxSpecList(res.data);
    });
  };

  const changeFileNum = (id: string, value: number, idx: number) => {
    // 计算从第几条开始取值
    const fileIdx: number =
      idx === 0
        ? 0
        : boxList
            .slice(0, idx)
            .map((item) => item.fileNum || 0)
            .reduce((pre, cur) => pre + cur);

    const entryObjs: any[] = selectObjs.slice(fileIdx, fileIdx + value);
    const entryIds: number[] = entryObjs.map((item) => item.id);
    const sumPageNum: number = entryObjs
      .map((item) => item.file_page_count || 0)
      .reduce((pre, cur) => pre + cur);
    const selectBox: BoxInfo = selectItemByKey(id, boxList);
    selectBox.setFileNum(value, sumPageNum, entryIds);

    setBoxList((list) => editItemById(id, selectBox, list));
  };

  const changeBoxSpec = (id: string, specId: number) => {
    const selectBox: BoxInfo = selectItemByKey(id, boxList);
    selectBox.setSpecId(specId);
    setBoxList((list) => editItemById(id, selectBox, list));
  };

  const specBox2ArcBox = (
    specId: number,
    fileCount: number,
    filePageCount: number
  ): IArchiveBox => {
    const boxSpec = selectItemByKey(specId, boxSpecList) || {};
    const { id, code, name } = boxSpec;
    return {
      archiveBoxSpecId: id,
      boxCode: code,
      boxName: name,
      fileCount,
      filePageCount
    };
  };

  const saveBoxInfo = () => {
    const params: IPackBoxParams[] = boxList.map((item) => ({
      archiveTypeId: baseInfo.archiveTypeId,
      commonParams: baseInfo.param.commonParams,
      level: 1,
      entryIdList: item.entryIdList,
      archiveBox: specBox2ArcBox(item.specId, item.fileNum, item.pageNum)
    }));
    packBoxMethod(params).then(() => {
      message.success('分盒成功');
      onClose();
    });
  };

  const specOptions = boxSpecList.map((box) => ({ label: box.name, value: box.id }));

  return (
    <Modal
      visible={visible}
      title="分盒"
      width={700}
      onCancel={onClose}
      footer={[
        <Button onClick={onClose} key="cancel">
          取消
        </Button>,
        <Button
          onClick={() => {
            saveBoxInfo();
          }}
          key="save"
        >
          保存
        </Button>
      ]}
    >
      <div className="box-num">
        <p>（共有文件{selectObjs.length}个）</p>
        <Space>
          共分
          <InputNumber
            value={boxNum}
            min={1}
            max={Math.max(selectObjs.length, 1)}
            onChange={(value: number) => {
              setBoxNum(value);
            }}
          />
          盒
        </Space>
      </div>
      <Divider />
      <div className="split-wrap">{/* <p>用鼠标拖动滑块对各盒中存放的文件进行分配</p> */}</div>
      <div className="box-info-list">
        {boxList.map((item, idx: number) => (
          <Space key={item.id}>
            <span>第{idx + 1}盒</span>
            {item.entryIdList?.length > 0 && (
              <span>
                #{item.entryIdList[0]} ~ #{item.entryIdList[item.entryIdList.length - 1]}，
              </span>
            )}
            <Space>
              共{' '}
              <InputNumber
                size="small"
                min={1}
                max={Math.max(selectObjs.length, 1)}
                onChange={(value: number) => {
                  changeFileNum(item.id, value, idx);
                }}
              />
              个文件{item.pageNum}页
            </Space>
            <Select
              options={specOptions}
              size="small"
              style={{ width: 120 }}
              onChange={(value: number) => {
                changeBoxSpec(item.id, value);
              }}
            />
          </Space>
        ))}
      </div>
    </Modal>
  );
};
export default PackBoxDialog;
